/*
 * @description: 动态路由
 * @Author: Islands
 * @Date: 2024-06-17 18:48:08
 * @LastEditTime: 2024-08-22 20:19:26
 */
import router from '@/plugins/router/index';
import { storeToRefs } from "pinia";
import { authorizeStore } from '@/plugins/pinia/index';
import NProgress from 'nprogress';  //进度条组件 yarn add nprogress
import 'nprogress/nprogress.css';   //进度条组件样式
import { RoutesEnum } from '@/enum/index'
/**
 * @description: 1.前置守卫
 * @author: Islands
 * @param {*} to 即将要进入的目标
 * @param {any} from 当前导航正要离开的路由
 * @param {any} next    路由的控制参数，常用的有next(true)和next(false)
 * @return {*}
 */
router.beforeEach(async (to: any, from: any, next: any) => {
    NProgress.start();    
    const { accountToken, whitelistPath } = storeToRefs(authorizeStore());
    //1.白名单直接加载
    if (whitelistPath.value.includes(to.path)) return next();
    //2.如果用户没有登陆，去获取token
    const { getAccountToken, getRoutes } = authorizeStore();
    if (!accountToken.value) {
        return await getAccountToken ?
            next({ path: to.fullPath, replace: true }) :
            next({ path: RoutesEnum.LOGIN_REDIRECT, query: { redirect: to.fullPath } });
    };
    //3.如果已登陆，在访问 /login 直接进入首页
    if (from.path === RoutesEnum.LOGIN_REDIRECT || to.path === RoutesEnum.LOGIN_REDIRECT) return next({ path: RoutesEnum.HOME });
    //4.判断是否已加载动态路由  
    if(router.getRoutes().filter(record=>record.path===to.path).length>0){
        return next();
    }
    //5. 加载动态路由
    const accessedRoutes = await getRoutes;
    accessedRoutes.forEach((route: any) => {
        router.addRoute(route);
    });
    return next({ ...to, replace: true })
});

/**
 * @description: 2.全局后置守卫
 * @author: Islands
 * @param {any} to
 * @param {any} from
 * @return {*}
 */
router.afterEach((to: any, from: any) => {
    //设置跳转路由后页面的标题
    document.title = (to.meta.title ? to.meta.title : 'Saa平台');
    //此处可以处理调用接口处理日志等
    NProgress.done();
});




